/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chatsoft.server.buz;

import ChatSoft.model.ConnectChatVoiceMessage;
import ChatSoft.model.ConnectFileMessage;
import ChatSoft.model.FileMessage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author VinhThien
 */
public class FileBusiness extends Thread {
    public ServerSocket server_socket;

    public FileBusiness() throws IOException {
        server_socket = new ServerSocket(7777);
    }

    public void closeSocket() throws IOException {
        if (server_socket != null && !server_socket.isClosed()) {
            server_socket.close();
        }
    }

    @Override
    public void run() {
        try {
            try {
                while (!this.isInterrupted())//luon luon cho ket noi tu phia client
                {
                    Socket socket = server_socket.accept();
                    ObjectInputStream i = new ObjectInputStream(socket.getInputStream());
                    try {
 
                        Object obj = i.readObject();
                        if (obj instanceof ConnectFileMessage) {
                            ConnectFileMessage mes = (ConnectFileMessage) obj;
                            
                            OutputStream out = socket.getOutputStream();
                            ServerStaticVariable.fileOnlineStream.put(mes.getSendTo()+"."+mes.getReceiveFrom(), out);
                            ServerStaticVariable.socketFileOnlineStream.put(mes.getSendTo()+"."+mes.getReceiveFrom(), socket);
                        }
                        else if (obj instanceof FileMessage) {
                            FileMessage mes = (FileMessage) obj;
                            InputStream in = socket.getInputStream();
                            FileController us = new FileController(in, mes.getReceiveFrom()+"."+mes.getSendTo(), socket);
                            us.start();
                        }
                    } catch (ClassNotFoundException ex) {
                        Logger.getLogger(FileBusiness.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            } catch (Exception e) {
                System.out.println(e);
            }
            finally {
                closeSocket();
            }
        } catch (IOException ioe) {
            Logger.getLogger(ServerBussiness.class.getName()).log(Level.SEVERE, null, ioe);
        }
    }
}
